﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using System.Web;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using BIZModel;
using BIZMA.BL;

namespace BIZMA
{
    /// <summary>
    /// Generate thumbnail for an image
    /// </summary>
    public partial class Thumb : System.Web.UI.Page
    {
        private const int DefaultMaxWidth = 90;
        private const int DefaultMaxHeight = 70;

        private const string ParamWidth = "w";
        private const string ParamHeight = "h";
        private const string ParamImage = "img";
        private const string ParamId = "id";

        private double maxWidth = DefaultMaxWidth;
        private double maxHeight = DefaultMaxHeight;

        //private string libraryRoot = string.Empty;
        //private string docLibraryRoot = string.Empty;
        private string fullSizeImageUrl = string.Empty;
        private Guid fileGuid = Guid.Empty;
        private bool isImage = true;
        private BIZModel.File fileData = null;

        protected void Page_Load(object sender, System.EventArgs e)
        {

            SetParameters();


            if (fileGuid != Guid.Empty)
            {
                BIZMAEntities ent = BaseBL.GetEnt();

                fileData = ent.Files.FirstOrDefault(q => q.FileId == fileGuid);

                if (fileData != null)
                {
                    //Hämtar en icon för filtypen istället om det inte är en bild 
                    //if (!fileData.ContentType.ToLower().StartsWith("image"))
                    if(fileData.FileTypeId == FileTypeKeys.FILE.ToString())
                    {
                        fullSizeImageUrl = GetFileImageUrl(fileData.FileName);
                        isImage = false;
                    }
                }
            }
            else
            {
                if (GetContentType(fullSizeImageUrl).Length == 0)
                {
                    fullSizeImageUrl = GetFileImageUrl(fullSizeImageUrl);
                    isImage = false;
                }

            }

            WriteThumbnail();
        }

        /// <summary>
        /// Read request parameters 
        /// </summary>
        private void SetParameters()
        {
            object tmp = null;

            // Get URL to full size image 
            fullSizeImageUrl = Request.QueryString[ParamImage];
            string id = Request.QueryString[ParamId];

            if (!string.IsNullOrEmpty(id))
            {
                fileGuid = Guid.Parse(id);
            }



            #region Calc Image Height/Width

            // Get thumbnail width
            tmp = Request.QueryString[ParamWidth];
            if (tmp != null)
            {
                try
                {
                    maxWidth = Convert.ToInt32(tmp);
                }
                catch (Exception err)
                {
                    maxWidth = DefaultMaxWidth;
                    Trace.Write(err.Message);
                }
            }

            // Get thumbnail height
            tmp = Request.QueryString[ParamHeight];
            if (tmp != null)
            {
                try
                {
                    maxHeight = Convert.ToInt32(tmp);
                }
                catch (Exception err)
                {
                    maxHeight = DefaultMaxHeight;
                    Trace.Write(err.Message);
                }
            }
            #endregion
        }
        private string GetFileImageUrl(string path)
        {
            switch (Path.GetExtension(path).ToLower())
            {
                case ".doc":
                case ".docx":
                    return ResolveUrl("~/images/file_type_icon/icon-file-doc-70-on.gif");
                case ".video": return ResolveUrl("~/images/file_type_icon/icon-file-video-70-on.gif");
                case ".audio": return ResolveUrl("~/images/file_type_icon/icon-file-audio-70-on.gif");
                case ".pdf": return ResolveUrl("~/images/file_type_icon/icon-file-pdf-70-on.gif");
                case ".ppt": return ResolveUrl("~/images/file_type_icon/icon-file-ppt-70-on.gif");
                case ".xls":
                case ".xlsx":
                    return ResolveUrl("~/images/file_type_icon/icon-file-xls-70-on.gif");
                default: return ResolveUrl("~/images/file_type_icon/icon-file-general-70-on.gif");
            }
        }

        private string GetContentType(string path)
        {
            switch (Path.GetExtension(path).ToLower())
            {
                case ".bmp": return "Image/bmp";
                case ".gif": return "Image/gif";
                case ".jpg": return "Image/jpeg";
                case ".jpeg": return "Image/jpeg";
                case ".png": return "Image/png";
                default: break;
            }
            return "";
        }

        private ImageFormat GetImageFormat(string path)
        {
            switch (Path.GetExtension(path).ToLower())
            {


                case ".bmp": return ImageFormat.Bmp;
                case ".gif": return ImageFormat.Gif;
                case ".jpg": return ImageFormat.Jpeg;
                case ".jpeg": return ImageFormat.Jpeg;
                case ".png": return ImageFormat.Png;
                default: break;
            }
            return ImageFormat.Jpeg;
        }


        /// <summary>
        ///  Calculates the size of the thumbnail image.
        /// </summary>
        /// <param name="height">Parameter that will recieve the height of the thumbnail</param>
        /// <param name="width">Parameter that will recieve the width of the thumbnail</param>
        /// <param name="originalImage">Full-size image</param>
        private void CalculateThumbnailSize(out int height, out int width, System.Drawing.Image originalImage)
        {
            double originalHeight = originalImage.Height;
            double originalWidth = originalImage.Width;
            width = originalImage.Width;
            height = originalImage.Height;

            if ((originalWidth > maxWidth) || (originalHeight > maxHeight))
            {
                if ((maxWidth / maxHeight) < (originalWidth / originalHeight))
                {
                    width = Convert.ToInt32(maxWidth);
                    height = Convert.ToInt32((maxWidth / originalWidth) * originalHeight);
                }
                else
                {
                    height = Convert.ToInt32(maxHeight);
                    width = Convert.ToInt32((maxHeight / originalHeight) * originalWidth);
                }
            }
        }

        /// <summary>
        /// Dummy callback, called by Image.GetThumbnailImage
        /// </summary>
        /// <returns>false</returns>
        public bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// Writes a thumbnail of the specified image to the output stream
        /// </summary>
        /// <param name="imageUrl">URL to full-size image</param>
        private void WriteThumbnail()
        {
            int thumbWidth;
            int thumbHeight;
            System.Drawing.Image originalImage = null;


            if (fileData != null && isImage)
            {

                MemoryStream MS = new MemoryStream(fileData.FileData);
                originalImage = System.Drawing.Image.FromStream(MS);

                Response.AddHeader("Content-Disposition", "filename=" + fileData.FileName);


            }
            else
            {
                originalImage = System.Drawing.Image.FromFile(Server.MapPath(fullSizeImageUrl));
            }



            if (originalImage != null)
            {
                if (originalImage.Width > maxWidth || originalImage.Height > maxHeight)
                {
                    CalculateThumbnailSize(out thumbHeight, out thumbWidth, originalImage);
                    System.Drawing.Image thumbnailImage;
                    if (maxWidth < 120 && maxHeight < 120)
                    {
                        System.Drawing.Image.GetThumbnailImageAbort dummyCallback;
                        dummyCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

                        thumbnailImage = originalImage.GetThumbnailImage(thumbWidth, thumbHeight, dummyCallback, IntPtr.Zero);
                    }
                    else
                    {
                        Bitmap bm = new Bitmap(originalImage);
                        Bitmap tn = ImageFilter.ImageResize(bm, new Size(thumbWidth, thumbHeight));
                        bm.Dispose();
                        thumbnailImage = Image.FromHbitmap(tn.GetHbitmap());
                        tn.Dispose();
                    }

                    Response.ContentType = "image/jpeg";
                    thumbnailImage.Save(Response.OutputStream, ImageFormat.Jpeg);
                    thumbnailImage.Dispose();
                }
                else
                {

                    if (fileData != null && isImage)
                    {
                        Response.ContentType = fileData.ContentType;
                        Response.BinaryWrite(fileData.FileData);

                    }
                    else
                    {
                        // Make sure that a file with GIF extension contains a GIF image.
                        if (originalImage.RawFormat.Guid != ImageFormat.Gif.Guid && GetContentType(fullSizeImageUrl) == "Image/gif" || GetContentType(fullSizeImageUrl) == "Image/png")
                        {
                            MemoryStream memStream = new MemoryStream();
                            //Set the content type
                            Response.ContentType = "image/png";
                            originalImage.Save(memStream, ImageFormat.Png);
                            memStream.WriteTo(Response.OutputStream);
                        }
                        else
                        {
                            Response.ContentType = GetContentType(fullSizeImageUrl);
                            originalImage.Save(Response.OutputStream, GetImageFormat(fullSizeImageUrl));
                        }
                    }

                }
                originalImage.Dispose();
            }


        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }
        #endregion
    }
}